package cn.iocoder.yudao.module.shop.service.order.handler;

import cn.iocoder.yudao.module.shop.controller.admin.itemconsume.ShopItemConsumeRespVO;
import cn.iocoder.yudao.module.shop.dal.dataobject.order.ShopOrderDO;
import cn.iocoder.yudao.module.shop.dal.dataobject.order.ShopOrderItemDO;
import cn.iocoder.yudao.module.shop.enums.store.StoreBizTypeEnum;
import cn.iocoder.yudao.module.shop.service.itemconsume.ShopItemConsumeService;
import cn.iocoder.yudao.module.shop.service.store.StoreService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * 库存消耗 {@link ShopOrderHandler} 实现类
 *
 * @author 曹建伟
 */

@Component
public class StoreShopOrderHandler implements ShopOrderHandler{

    @Resource
    private ShopItemConsumeService shopItemConsumeService;

    @Resource
    private StoreService storeService;

    @Override
    public void afterPayOrder(ShopOrderDO order, List<ShopOrderItemDO> shopOrderItems) {
        List<Long> itemIds = new ArrayList<>();
        for (ShopOrderItemDO shopOrderItem : shopOrderItems) {
            itemIds.add(shopOrderItem.getOptItemId());
        }

        String purpose = "店内消耗";
        List<ShopItemConsumeRespVO> shopItemConsumeRespVOS = shopItemConsumeService.getList(itemIds);
        shopItemConsumeRespVOS.forEach(shopItemConsumeRespVO -> {
            storeService.consume(shopItemConsumeRespVO.getStoreItem().getId(), shopItemConsumeRespVO.getCount(), StoreBizTypeEnum.SHOPORDER_CHECK.getType(), order.getTenantId(), order.getStartTime(), purpose);
        });
    }

    @Override
    public void rollbackOrder(ShopOrderDO order, List<ShopOrderItemDO> shopOrderItems){
        if(!order.getWalletCharge()){
            return;
        }

        List<Long> itemIds = new ArrayList<>();
        for (ShopOrderItemDO shopOrderItem : shopOrderItems) {
            itemIds.add(shopOrderItem.getOptItemId());
        }

        String purpose = "核销回退";
        List<ShopItemConsumeRespVO> shopItemConsumeRespVOS = shopItemConsumeService.getList(itemIds);
        shopItemConsumeRespVOS.forEach(shopItemConsumeRespVO -> {
            storeService.consume(shopItemConsumeRespVO.getStoreItem().getId(), -shopItemConsumeRespVO.getCount(), StoreBizTypeEnum.SHOPORDER_ROLLBACK.getType(), order.getTenantId(), order.getStartTime(), purpose);
        });
    }
}
